package net.wesc.ac.server;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.wesc.ac.client.MainPanel;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

import Jama.Matrix;

public class ExpPlotServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 4993680464858090895L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		HttpSession session =request.getSession();
		String data = (String)session.getAttribute("data");
		String model = (String)session.getAttribute("model");
		if(data==null || model==null){
			return;
		}
		else{
			session.removeAttribute("data");
			session.removeAttribute("model");
		}
		
		double[][] expdata = Data.getData(data);
		try{
			JFreeChart chart = createChart(expdata, model);
			response.setContentType("image/png");
			ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, 600, 520);
		}
		finally{

		}
	}
	
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		doGet(request, response);
	}
	
	private XYDataset createDataset(double[][] data, String model){
		XYSeries xyseries = new XYSeries("Exp");
		int i=0;
		int rows = (new Matrix(data)).getRowDimension();
		while(i<rows){
			if(model.matches(MainPanel.RS_EQUATION)){
				xyseries.add(data[i][0], data[i][2]);
			}
			else{
				xyseries.add(data[i][0], data[i][1]);
			}
			i++;
		}
        
        XYSeriesCollection xySeriesCollection = new XYSeriesCollection();
        xySeriesCollection.addSeries(xyseries);
        return xySeriesCollection;
	}
	
	private JFreeChart createChart(double[][] data, String model){
    	XYDataset dataset = createDataset(data, model);
    	JFreeChart chart = ChartFactory.createScatterPlot("Relation Between ln(r) and molality", "molality mol/kg(H2O)", "log(r)", dataset, PlotOrientation.VERTICAL, false, false, true);
    	return chart;
	}
}